package org.String;

import org.Utils.IOUtils;

import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.StringJoiner;

import static org.Utils.IOUtils.buildInsertSql;
import static org.Utils.IOUtils.buildSelectSql;

public class TestString {
    public static void testFormat() {
        String s = "Hi %s, your score is %d!";
        // java 17
//        System.out.println(s.formatted("Alice", 80));
        String formatString = String.format("Hi %s, your score is %.2f!", "Bob", 59.5);
        System.out.println(formatString);

        System.out.println("".isEmpty());
        System.out.println(Integer.getInteger("JAVA_HOME"));
    }

    public static void testEncoding() {
        try {
            byte[] b1 = "种Hello".getBytes(); // 按系统默认编码转换，不推荐
            byte[] b2 = "种Hello".getBytes("UTF-8"); // 按UTF-8编码转换
            byte[] b3 = "种Hello".getBytes("GBK"); // 按GBK编码转换
            byte[] b4 = "种Hello".getBytes(StandardCharsets.UTF_8); // 按UTF-8编码转换

            System.out.printf("Default coding = %s\n", IOUtils.getByteArrays(b1));
            System.out.printf("UTF-8 coding = %s\n", IOUtils.getByteArrays(b2));
            System.out.printf("GBK coding = %s\n", IOUtils.getByteArrays(b3));
            System.out.printf("UTF-8 2 coding = %s\n", IOUtils.getByteArrays(b4));
        } catch (UnsupportedEncodingException ignored) {

        }
    }

    public static void testInsertSql() {
        String[] fields = { "name", "position", "salary" };
        String table = "employee";
        String insert = buildInsertSql(table, fields);
        System.out.println(insert);
        String s = "INSERT INTO employee (name, position, salary) VALUES (?, ?, ?)";
        System.out.println(s.equals(insert) ? "测试成功" : "测试失败");
    }

    public static void testStringJoin() {
        String[] names = {"Bob", "Alice", "Grace"};
        StringBuilder sb = new StringBuilder();
        sb.append("Hello ");
        for (String name : names) {
            sb.append(name).append(", ");
        }
        // 注意去掉最后的", ":
        sb.delete(sb.length() - 2, sb.length());
        sb.append("!");
        System.out.println(sb.toString());
    }

    public static void testStringJoiner() {
        String[] names = {"Bob", "Alice", "Grace"};
        StringJoiner sj = new StringJoiner(", ", "Hello ", "!");
        for (String name : names) {
            sj.add(name);
        }
        System.out.println(sj.toString());
    }

    public static void testSelectSql() {
        String[] fields = { "name", "position", "salary" };
        String table = "employee";
        String select = buildSelectSql(table, fields);
        System.out.println(select);
        System.out.println("SELECT name, position, salary FROM employee".equals(select) ? "测试成功" : "测试失败");
    }
}